<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/hexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="开发笔记,">










<meta name="description" content="自从知道Redis之后，近两年几乎所有的项目都会用到，而且Redis也确实非常好用！。最近在各类公众号文章上发现关于Redis技术迭代和落地到具体项目的内容越来越多，自己最近也是小有所悟，总结一下，希望各位大神指教。大家都知道，Redis是一个非关系型的，key-value数据库，高效，简单，支持多种数据类型，string(字符串),list(列表),hash(哈希),set(集合),zset(有">
<meta name="keywords" content="开发笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="一次关于在Redis的使用上的进阶经历">
<meta property="og:url" content="https://tony_df.coding.net/2019/02/25/一次关于在Redis的使用上的进阶经历/index.html">
<meta property="og:site_name" content="Tony&#39;s blog">
<meta property="og:description" content="自从知道Redis之后，近两年几乎所有的项目都会用到，而且Redis也确实非常好用！。最近在各类公众号文章上发现关于Redis技术迭代和落地到具体项目的内容越来越多，自己最近也是小有所悟，总结一下，希望各位大神指教。大家都知道，Redis是一个非关系型的，key-value数据库，高效，简单，支持多种数据类型，string(字符串),list(列表),hash(哈希),set(集合),zset(有">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tony_df.coding.net/2019/02/25/一次关于在Redis的使用上的进阶经历/1.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/02/25/一次关于在Redis的使用上的进阶经历/2.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/02/25/一次关于在Redis的使用上的进阶经历/3.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/02/25/一次关于在Redis的使用上的进阶经历/4.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/02/25/一次关于在Redis的使用上的进阶经历/5.png">
<meta property="og:updated_time" content="2019-04-17T03:12:35.852Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="一次关于在Redis的使用上的进阶经历">
<meta name="twitter:description" content="自从知道Redis之后，近两年几乎所有的项目都会用到，而且Redis也确实非常好用！。最近在各类公众号文章上发现关于Redis技术迭代和落地到具体项目的内容越来越多，自己最近也是小有所悟，总结一下，希望各位大神指教。大家都知道，Redis是一个非关系型的，key-value数据库，高效，简单，支持多种数据类型，string(字符串),list(列表),hash(哈希),set(集合),zset(有">
<meta name="twitter:image" content="https://tony_df.coding.net/2019/02/25/一次关于在Redis的使用上的进阶经历/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hexo/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Tony'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tony_df.coding.net/2019/02/25/一次关于在Redis的使用上的进阶经历/">





  <title>一次关于在Redis的使用上的进阶经历 | Tony's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hexo/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学着码代码,学着码人生;</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tony_df.coding.net/hexo/2019/02/25/一次关于在Redis的使用上的进阶经历/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hexo/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">一次关于在Redis的使用上的进阶经历</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-02-25T14:34:55+08:00">
                2019-02-25
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>自从知道Redis之后，近两年几乎所有的项目都会用到，而且Redis也确实非常好用！。<br>最近在各类公众号文章上发现关于Redis技术迭代和落地到具体项目的内容越来越多，自己最近也是小有所悟，总结一下，希望各位大神指教。<br>大家都知道，Redis是一个非关系型的，key-value数据库，高效，简单，支持多种数据类型，string(字符串),list(列表),hash(哈希),set(集合),zset(有序集合)，为了保证效率，数据都是缓存在内存中。<br>而且Redis还会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件，所以Redis支持持久化存储，并且在此基础上实现了master-slave(主从)同步。<br>对外Redis还提供的多种开发语言的接口，包括今天我们所要说的C#语言，值得一提的是，它还支持JavaScript！<br>刚了解到Redis的时候，参照前人的例子，简单写过一个类函数，在项目中几乎就把Redis当成了一个公共哈希表来用，用法简单，适用的场景也很少，但也确实能实在的解决很多问题，比如服务端的Session共享问题<br>这段只用到Redis初级功能的代码如下(依赖StackExchange所做的封装,StackExchange是.net环境下一款免费，开源的Redis操作包，是当前.net使用访问Redis的主流类库)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line">public class RedisHelper</span><br><span class="line">&#123;</span><br><span class="line">	private static string _conn = ConfigurationManager.AppSettings[&quot;Redis&quot;] ?? &quot;127.0.0.1:6379&quot;;        </span><br><span class="line">	public static string StringGet(string key)</span><br><span class="line">	&#123;</span><br><span class="line">		try</span><br><span class="line">		&#123;</span><br><span class="line">			using (var client = ConnectionMultiplexer.Connect(_conn))</span><br><span class="line">			&#123;</span><br><span class="line">				return client.GetDatabase().StringGet(key);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		catch (Exception)</span><br><span class="line">		&#123;</span><br><span class="line">			return null;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public static string[] StringGetMany(string[] keyStrs)</span><br><span class="line">	&#123;</span><br><span class="line">		var count = keyStrs.Length;</span><br><span class="line">		var keys = new RedisKey[count];</span><br><span class="line">		var addrs = new string[count];</span><br><span class="line">		for (var i = 0; i &lt; count; i++)</span><br><span class="line">		&#123;</span><br><span class="line">			keys[i] = keyStrs[i];</span><br><span class="line">		&#125;</span><br><span class="line">		try</span><br><span class="line">		&#123;</span><br><span class="line">			using (var client = ConnectionMultiplexer.Connect(_conn))</span><br><span class="line">			&#123;</span><br><span class="line">				var values = client.GetDatabase().StringGet(keys);</span><br><span class="line">				for (var i = 0; i &lt; values.Length; i++)</span><br><span class="line">				&#123;</span><br><span class="line">					addrs[i] = values[i];</span><br><span class="line">				&#125;</span><br><span class="line">				return addrs;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		catch (Exception)</span><br><span class="line">		&#123;</span><br><span class="line">			return null;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/// &lt;summary&gt;</span><br><span class="line">	/// 单条存值</span><br><span class="line">	/// &lt;/summary&gt;</span><br><span class="line">	/// &lt;param name=&quot;key&quot;&gt;key&lt;/param&gt;</span><br><span class="line">	/// &lt;param name=&quot;value&quot;&gt;The value.&lt;/param&gt;</span><br><span class="line">	/// &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if XXXX, &lt;c&gt;false&lt;/c&gt; otherwise.&lt;/returns&gt;</span><br><span class="line">	public static bool StringSet(string key, string value)</span><br><span class="line">	&#123;</span><br><span class="line">		using (var client = ConnectionMultiplexer.Connect(_conn))</span><br><span class="line">		&#123;</span><br><span class="line">			return client.GetDatabase().StringSet(key, value);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/// &lt;summary&gt;</span><br><span class="line">	/// 批量存值</span><br><span class="line">	/// &lt;/summary&gt;</span><br><span class="line">	/// &lt;param name=&quot;keysStr&quot;&gt;key&lt;/param&gt;</span><br><span class="line">	/// &lt;param name=&quot;valuesStr&quot;&gt;The value.&lt;/param&gt;</span><br><span class="line">	/// &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if XXXX, &lt;c&gt;false&lt;/c&gt; otherwise.&lt;/returns&gt;</span><br><span class="line">	public static bool StringSetMany(string[] keysStr, string[] valuesStr)</span><br><span class="line">	&#123;</span><br><span class="line">		var count = keysStr.Length;</span><br><span class="line">		var keyValuePair = new KeyValuePair&lt;RedisKey, RedisValue&gt;[count];</span><br><span class="line">		for (int i = 0; i &lt; count; i++)</span><br><span class="line">		&#123;</span><br><span class="line">			keyValuePair[i] = new KeyValuePair&lt;RedisKey, RedisValue&gt;(keysStr[i], valuesStr[i]);</span><br><span class="line">		&#125;</span><br><span class="line">		using (var client = ConnectionMultiplexer.Connect(_conn))</span><br><span class="line">		&#123;</span><br><span class="line">			return client.GetDatabase().StringSet(keyValuePair);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public static bool DelKey(string key)</span><br><span class="line">	&#123;</span><br><span class="line">		using (var client = ConnectionMultiplexer.Connect(_conn))</span><br><span class="line">		&#123;</span><br><span class="line">			return client.GetDatabase().KeyDelete(key);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	#region 泛型</span><br><span class="line">	/// &lt;summary&gt;</span><br><span class="line">	/// 存值并设置过期时间</span><br><span class="line">	/// &lt;/summary&gt;</span><br><span class="line">	/// &lt;typeparam name=&quot;T&quot;&gt;&lt;/typeparam&gt;</span><br><span class="line">	/// &lt;param name=&quot;key&quot;&gt;key&lt;/param&gt;</span><br><span class="line">	/// &lt;param name=&quot;t&quot;&gt;实体&lt;/param&gt;</span><br><span class="line">	/// &lt;param name=&quot;ts&quot;&gt;过期时间间隔&lt;/param&gt;</span><br><span class="line">	/// &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if XXXX, &lt;c&gt;false&lt;/c&gt; otherwise.&lt;/returns&gt;</span><br><span class="line">	public static bool Set&lt;T&gt;(string key, T t, TimeSpan ts)</span><br><span class="line">	&#123;</span><br><span class="line">		var str = JsonConvert.SerializeObject(t);</span><br><span class="line">		using (var client = ConnectionMultiplexer.Connect(_conn))</span><br><span class="line">		&#123;</span><br><span class="line">			return client.GetDatabase().StringSet(key, str, ts);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/// &lt;summary&gt;</span><br><span class="line">	///</span><br><span class="line">	/// 根据Key获取值</span><br><span class="line">	/// &lt;/summary&gt;</span><br><span class="line">	/// &lt;typeparam name=&quot;T&quot;&gt;&lt;/typeparam&gt;</span><br><span class="line">	/// &lt;param name=&quot;key&quot;&gt;The key.&lt;/param&gt;</span><br><span class="line">	/// &lt;returns&gt;T.&lt;/returns&gt;</span><br><span class="line">	public static T Get&lt;T&gt;(string key) where T : class</span><br><span class="line">	&#123;</span><br><span class="line">		using (var client = ConnectionMultiplexer.Connect(_conn))</span><br><span class="line">		&#123;</span><br><span class="line">			var strValue = client.GetDatabase().StringGet(key);</span><br><span class="line">			return string.IsNullOrEmpty(strValue) ? null : JsonConvert.DeserializeObject&lt;T&gt;(strValue);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	#endregion</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>用起来也十分简单，比如我要缓存某个用户的登录信息时</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">RedisHelper.Set&lt;string&gt;(&quot;session_key&quot; + loginCode, session_key, DateTime.Now.AddMinutes(10) - DateTime.Now);</span><br></pre></td></tr></table></figure>

<p>读取的时候</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">string session_key = RedisHelper.Get&lt;string&gt;(&quot;session_key&quot; + loginCode);</span><br></pre></td></tr></table></figure>

<p>只需保证键值唯一就好，用起来就像使用哈希表或字典那样简单；<br>但是近期，我遇到了一个稍微复杂一点的需求，单纯的依靠上面这个类是难以实现的，而如果不借助Redis，效率又会很差（目前能力范围内~~），所以还是决定使用Redis<br>先简单描述一下需求<br>有一堆报单审批表，每个报单有多个审批流程，涉及到客户和服务人员的交互操作，而每个报单都有其对应的审批人员，报单不能同时被两个审批人员审批，特殊管理人员除外，<br>需要做的是要在每次审批人员登录系统的时候，会有提示，告诉审批人员哪些报单是可以现在审批的，说白了就是省去审批人员每次都要挨个去查哪些报单是他审批的，他审批的报单里哪些又有新的动态。</p>
<p>那么这个问题怎么来解决呢，相信各位会有很多非常优秀的方案，这篇讲Redis，我就分享一下我的解决办法<br>首先稍微改造下上面那个类，关于初始化Redis链接的部分代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">private static readonly string ConnectionString;</span><br><span class="line">//private static string ConnectionString = ConfigurationManager.AppSettings[&quot;Redis&quot;] ?? &quot;127.0.0.1:6379&quot;;      </span><br><span class="line">private static Logger logger = LogManager.GetCurrentClassLogger();//日志记录类</span><br><span class="line"> /// &lt;summary&gt;</span><br><span class="line">/// redis 连接对象</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">private static IConnectionMultiplexer _connMultiplexer;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 默认的 Key 值（用来当作 RedisKey 的前缀）</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">private static readonly string DefaultKey;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 锁</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">private static readonly object Locker = new object();</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 数据库</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">private readonly IDatabase _db;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 获取 Redis 连接对象</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public IConnectionMultiplexer GetConnectionRedisMultiplexer()</span><br><span class="line">&#123;</span><br><span class="line">	if ((_connMultiplexer == null) || !_connMultiplexer.IsConnected)</span><br><span class="line">	&#123;</span><br><span class="line">		lock (Locker)</span><br><span class="line">		&#123;</span><br><span class="line">			if ((_connMultiplexer == null) || !_connMultiplexer.IsConnected)</span><br><span class="line">				_connMultiplexer = ConnectionMultiplexer.Connect(ConnectionString);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	return _connMultiplexer;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#region 其它</span><br><span class="line"></span><br><span class="line">public ITransaction GetTransaction()</span><br><span class="line">&#123;</span><br><span class="line">	return _db.CreateTransaction();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#endregion 其它</span><br><span class="line"></span><br><span class="line">#region 构造函数</span><br><span class="line"></span><br><span class="line">static RedisHelper()</span><br><span class="line">&#123;</span><br><span class="line">	ConnectionString = ConfigurationManager.AppSettings[&quot;Redis&quot;] ?? &quot;127.0.0.1:6379&quot;; ;</span><br><span class="line">	_connMultiplexer = ConnectionMultiplexer.Connect(ConnectionString);</span><br><span class="line">	DefaultKey = ConfigurationManager.AppSettings[&quot;Redis.DefaultKey&quot;] ?? &quot;Tony&apos;s RedisHelper&quot;;</span><br><span class="line">	AddRegisterEvent();//注册事件，如发生内部错误时，记录一下日志等</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public RedisHelper(int db = -1)</span><br><span class="line">&#123;</span><br><span class="line">	_db = _connMultiplexer.GetDatabase(db);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#endregion 构造函数</span><br></pre></td></tr></table></figure>

<p>然后再来封装一些具体的操作，之前的那些简单的存取就不介绍了，我在这个问题中只用到了hash，而集合，列表与之类似，这里只说一下关于hash的操作，因为几乎囊括了原生Redis关于hash的所有操作，包括，单条存值，<br>多条存值，key,移除，且所有方法都有对应的异步方法，所以这段代码会比较长</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br></pre></td><td class="code"><pre><span class="line">#region Hash 操作</span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 判断该字段是否存在 hash 中</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public bool HashExists(string redisKey, string hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return _db.HashExists(redisKey, hashField);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 从 hash 中移除指定字段</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public bool HashDelete(string redisKey, string hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return _db.HashDelete(redisKey, hashField);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 从 hash 中移除指定字段</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public long HashDelete(string redisKey, IEnumerable&lt;RedisValue&gt; hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return _db.HashDelete(redisKey, hashField.ToArray());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 设定值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public bool HashSet(string redisKey, string hashField, string value)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return _db.HashSet(redisKey, hashField, value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 中设定值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashFields&quot;&gt;&lt;/param&gt;</span><br><span class="line">public void HashSet(string redisKey, IEnumerable&lt;HashEntry&gt; hashFields)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	_db.HashSet(redisKey, hashFields.ToArray());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 中获取值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public RedisValue HashGet(string redisKey, string hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return _db.HashGet(redisKey, hashField);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 中获取值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public RedisValue[] HashGet(string redisKey, RedisValue[] hashField, string value)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return _db.HashGet(redisKey, hashField);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 从 hash 返回所有的字段值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public IEnumerable&lt;RedisValue&gt; HashKeys(string redisKey)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return _db.HashKeys(redisKey);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 返回 hash 中的所有值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public RedisValue[] HashValues(string redisKey)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return _db.HashValues(redisKey);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 设定值（序列化）</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public bool HashSet&lt;T&gt;(string redisKey, string hashField, T value)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	//var json = Serialize(value);</span><br><span class="line">	var json = JsonHelper.ObjectToJSON(value);</span><br><span class="line">	return _db.HashSet(redisKey, hashField, json);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 中获取值（反序列化）</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public T HashGet&lt;T&gt;(string redisKey, string hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return JsonHelper.JSONToObject&lt;T&gt;(_db.HashGet(redisKey, hashField));</span><br><span class="line">	//return Deserialize&lt;T&gt;(_db.HashGet(redisKey, hashField));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#region async</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 判断该字段是否存在 hash 中</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;bool&gt; HashExistsAsync(string redisKey, string hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return await _db.HashExistsAsync(redisKey, hashField);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 从 hash 中移除指定字段</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;bool&gt; HashDeleteAsync(string redisKey, string hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return await _db.HashDeleteAsync(redisKey, hashField);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 从 hash 中移除指定字段</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;long&gt; HashDeleteAsync(string redisKey, IEnumerable&lt;RedisValue&gt; hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return await _db.HashDeleteAsync(redisKey, hashField.ToArray());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 设定值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;bool&gt; HashSetAsync(string redisKey, string hashField, string value)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return await _db.HashSetAsync(redisKey, hashField, value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 中设定值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashFields&quot;&gt;&lt;/param&gt;</span><br><span class="line">public async Task HashSetAsync(string redisKey, IEnumerable&lt;HashEntry&gt; hashFields)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	await _db.HashSetAsync(redisKey, hashFields.ToArray());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 中获取值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;RedisValue&gt; HashGetAsync(string redisKey, string hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return await _db.HashGetAsync(redisKey, hashField);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 中获取值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;IEnumerable&lt;RedisValue&gt;&gt; HashGetAsync(string redisKey, RedisValue[] hashField, string value)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return await _db.HashGetAsync(redisKey, hashField);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 从 hash 返回所有的字段值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;IEnumerable&lt;RedisValue&gt;&gt; HashKeysAsync(string redisKey)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return await _db.HashKeysAsync(redisKey);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 返回 hash 中的所有值</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;IEnumerable&lt;RedisValue&gt;&gt; HashValuesAsync(string redisKey)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return await _db.HashValuesAsync(redisKey);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 设定值（序列化）</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;bool&gt; HashSetAsync&lt;T&gt;(string redisKey, string hashField, T value)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	//var json = Serialize(value);</span><br><span class="line">	var json = JsonHelper.ObjectToJSON(value);</span><br><span class="line">	return await _db.HashSetAsync(redisKey, hashField, json);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 在 hash 中获取值（反序列化）</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;redisKey&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;hashField&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">public async Task&lt;T&gt; HashGetAsync&lt;T&gt;(string redisKey, string hashField)</span><br><span class="line">&#123;</span><br><span class="line">	redisKey = AddKeyPrefix(redisKey);</span><br><span class="line">	return Deserialize&lt;T&gt;(await _db.HashGetAsync(redisKey, hashField));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#endregion async</span><br><span class="line"></span><br><span class="line">#endregion Hash 操作</span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 添加 Key 的前缀</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;key&quot;&gt;&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">private static string AddKeyPrefix(string key)</span><br><span class="line">&#123;</span><br><span class="line">	//return $&quot;&#123;DefaultKey&#125;:&#123;key&#125;&quot;; //c# 6.0写法，更易读</span><br><span class="line">	return string.Format(&quot;&#123;0&#125;:&#123;1&#125;&quot;,DefaultKey,key);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>至此，完成上述需求的基础铺垫就完成了，应用的时候，我们只要再返回报单列表的时候，同时返回一个当前保单列表和缓存中存在的列表的差异列表就行了，<br>而当审批人员有新的审批修改之后，也需要同时修改缓存中的列表，具体的方法如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 生成差异的报单列表</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">private async Task&lt;List&lt;models.DeclarationRedisListModel&gt;&gt; InitApproverListAsync()</span><br><span class="line">&#123;</span><br><span class="line">	RedisHelper redis = new RedisHelper();</span><br><span class="line">	Model.manager adminInfo = new Web.UI.ManagePage().GetAdminInfo();</span><br><span class="line">	BLL.declaration BllDeclaration = new BLL.declaration();</span><br><span class="line">	int total = 0;</span><br><span class="line">	System.Data.DataSet ds = BllDeclaration.GetList(0, 0, &quot;approver=&apos;&quot; + adminInfo.user_name + &quot;&apos;&quot;, &quot;id&quot;, out total, &quot;id as declaration_id,status,order_code&quot;);</span><br><span class="line">	IList&lt;models.DeclarationRedisListModel&gt; list = Common.ModelConvertHelper&lt;models.DeclarationRedisListModel&gt;.ConvertToModel(ds.Tables[0]);   </span><br><span class="line">	if (!redis.HashExists(&quot;approverhash&quot;, adminInfo.user_name))</span><br><span class="line">	&#123;</span><br><span class="line">		await redis.HashSetAsync&lt;List&lt;models.DeclarationRedisListModel&gt;&gt;(&quot;approverhash&quot;, adminInfo.user_name, list.ToList());		</span><br><span class="line">		return list.ToList();</span><br><span class="line">	&#125;</span><br><span class="line">	else</span><br><span class="line">	&#123;                </span><br><span class="line">		List&lt;models.DeclarationRedisListModel&gt; list_orgin = redis.HashGet&lt;List&lt;models.DeclarationRedisListModel&gt;&gt;(&quot;approverhash&quot;, adminInfo.user_name);</span><br><span class="line">		List&lt;models.DeclarationRedisListModel&gt; exp = new List&lt;models.DeclarationRedisListModel&gt;();</span><br><span class="line">		for (int i = 0; i &lt; list.Count; i++)</span><br><span class="line">		&#123;</span><br><span class="line">			if (list_orgin.Exists(u =&gt; u.declaration_id == list[i].declaration_id))</span><br><span class="line">			&#123;</span><br><span class="line">				int new_status=list[i].status;</span><br><span class="line">				if (list_orgin.First(u =&gt; u.declaration_id == list[i].declaration_id).status != new_status)</span><br><span class="line">				&#123;</span><br><span class="line">					exp.Add(list[i]);</span><br><span class="line">				&#125;</span><br><span class="line">				else if (new_status &lt; 4 || new_status == 41 || new_status == 5 || new_status == 61 || new_status == 62)</span><br><span class="line">				&#123;</span><br><span class="line">					exp.Add(list[i]);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			else</span><br><span class="line">			&#123;</span><br><span class="line">				exp.Add(list[i]);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		await Task.Delay(100);</span><br><span class="line">		return exp;    </span><br><span class="line">	&#125;            </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 修改报单状态时，更新缓存</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">/// &lt;param name=&quot;admin&quot;&gt;当前操作人员&lt;/param&gt;</span><br><span class="line">/// &lt;param name=&quot;declaration_id&quot;&gt;报单id&lt;/param&gt;</span><br><span class="line">/// &lt;returns&gt;&lt;/returns&gt;</span><br><span class="line">private async Task UpdateApproverListAsync(string admin, int declaration_id)</span><br><span class="line">&#123;</span><br><span class="line">	RedisHelper redis = new RedisHelper();</span><br><span class="line">	BLL.declaration BllDeclaration = new BLL.declaration();</span><br><span class="line">	int total = 0;</span><br><span class="line">	System.Data.DataSet ds = BllDeclaration.GetList(0, 0, &quot;approver=&apos;&quot; + admin + &quot;&apos;&quot;, &quot;id&quot;, out total, &quot;id as declaration_id,status,order_code&quot;);</span><br><span class="line">	IList&lt;models.DeclarationRedisListModel&gt; list = Common.ModelConvertHelper&lt;models.DeclarationRedisListModel&gt;.ConvertToModel(ds.Tables[0]);</span><br><span class="line">	List&lt;models.DeclarationRedisListModel&gt; list_orgin = redis.HashGet&lt;List&lt;models.DeclarationRedisListModel&gt;&gt;(&quot;approverhash&quot;, admin);</span><br><span class="line">	int d_new_status = list.ToList().Find(u =&gt; u.declaration_id == declaration_id).status;//报单最新的状态值</span><br><span class="line">	if (list_orgin.Exists(u =&gt; u.declaration_id == declaration_id)) //如果存在该报单，但状态不一致，则修改状态</span><br><span class="line">	&#123;</span><br><span class="line">		list_orgin.Remove(list_orgin.Find(u =&gt; u.declaration_id == declaration_id));</span><br><span class="line">	&#125;</span><br><span class="line">	models.DeclarationRedisListModel model = new models.DeclarationRedisListModel()</span><br><span class="line">	&#123;</span><br><span class="line">		declaration_id = declaration_id,</span><br><span class="line">		status = d_new_status,</span><br><span class="line">		order_code = list.First(u =&gt; u.declaration_id == declaration_id).order_code</span><br><span class="line">	&#125;;</span><br><span class="line">	list_orgin.Add(model);</span><br><span class="line">	await  redis.HashSetAsync&lt;List&lt;models.DeclarationRedisListModel&gt;&gt;(&quot;approverhash&quot;, admin, list_orgin);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>好了，返回列表和审批的函数，我就不贴码了，至此我们要做的后端的工作就完成了，<br>配合前台的提醒插件spop</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"> if (res.explist) &#123;</span><br><span class="line">  for (var i = 0; i &lt; res.explist.length; i++) &#123;</span><br><span class="line">	  spop(&#123;</span><br><span class="line">		  template: &apos;有可审批的报单&lt;a href=&quot;./audit.aspx?id=&apos; + res.explist[i].declaration_id + &apos;&amp;order_code=&apos; + res.explist[i].order_code + &apos;&quot;&gt;&apos; + res.explist[i].order_code + &apos;&lt;/a&gt;&apos;,</span><br><span class="line">		  position: &apos;bottom-right&apos;,</span><br><span class="line">		  style: &apos;warning&apos;</span><br><span class="line">	  &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>工作就完成了~，其实后面实现需求的代码并不重要，因为你遇到的实际问题可能有很多种，而解决问题的关键就在于前面的铺垫，还是那句话，关于Redis的介绍这里只是冰山一角，如果您是没有接触过，或者初识Redis的同学<br>还是需要先去了解一下Redis的基本概念和简单操作，实际操作一下，非常有利于对Redis的理解，然后再在实际项目中应用的时候会事半功倍！（<br>）而关于Redis的基本教程，菜鸟教程上的内容我觉得还是非常不错的(<a href="http://www.runoob.com/redis/redis-tutorial.html)）" target="_blank" rel="noopener">http://www.runoob.com/redis/redis-tutorial.html)）</a><br>最后贴几张项目的图吧<br><img src="1.png" alt="1.png"><br><img src="2.png" alt="2.png"><br><img src="3.png" alt="3.png"></p>
<p><img src="4.png" alt="4.png"><br><img src="5.png" alt="5.png"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hexo/tags/开发笔记/" rel="tag"># 开发笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hexo/2019/01/31/分享一个处理视频文件的利器/" rel="next" title="分享一个处理视频文件的利器">
                <i class="fa fa-chevron-left"></i> 分享一个处理视频文件的利器
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hexo/2019/04/17/听君一席话/" rel="prev" title="听君一席话">
                听君一席话 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5bbb2338b87602f0" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTA1My8xNTU4MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description">学习总结</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hexo/archives/">
              
                  <span class="site-state-item-count">58</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hexo/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/hexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

</body>
</html>
